package com.changan.controller;

import com.changan.util.SecurityUtils;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserBackController extends Controller {

    public void index() {
        // 要注意/代表根目录
        render("login.jsp");
    }

    //实现登录操作
    public void login() {
        //Map<String, String[]> paraMap = new HashMap<>(getParaMap());
        //SqlPara login = Db.getSqlPara("login", paraMap);
        //SqlPara
        //String sql;  sql语句
        //List<Object> paraList;  参数
        String login_name = getPara("login_name");
        String user_password = getPara("user_password");
        SqlPara login = Db.getSqlPara("login", login_name, SecurityUtils.sha256Hex(user_password));
        List<Record> records = Db.find(login);
        System.out.println(records.size() + "===========");
        if (records.size() > 0) {//登录成功
            render("index.jsp");
        } else {
            setAttr("error", "用户名或者密码错误");
            render("login.jsp");//重定向到login.jsp
        }
    }

    /**
     * 分页查询所有的用户
     */
    public void selUsers(){
        //当前的页码
        String pageNumber = getPara("pageNumber");
        if(pageNumber==null){
            pageNumber="1";
        }
        String selUsers = Db.getSql("selUsers");
        SqlPara sqlPara = new SqlPara();
        sqlPara.setSql(selUsers);
        Page<Record> paginate = Db.paginate(Integer.parseInt(pageNumber), 2, sqlPara);
        setAttr("users",paginate);
        render("house_list.jsp");
    }

    public void del(){
        Db.delete("delete from user where user_id=?", getPara("user_id"));
        selUsers();
    }
}
